package com.drinks.yiniang.common.recycler.decoration;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import com.hansen.library.utils.ScreenSizeUtils;

/**
 * Created by han on 2019/3/19 0019.
 */

public class StaggeredItemDecoration extends RecyclerView.ItemDecoration {
    private int mFirstStaggeredPosition = -1;
    private int mSpace;

    public StaggeredItemDecoration(Context context, int space) {
        this.mSpace = ScreenSizeUtils.dp2px(context, space);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);

        StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();

        if(layoutParams != null && !layoutParams.isFullSpan()) {//判断是column=2的时候
            if(mFirstStaggeredPosition < 0) {
                mFirstStaggeredPosition = position;
            }

            //通过layoutposition设置会错乱，改成StaggeredGridLayoutManager.layoutParams.getSpanIndex()
            int spanIndex = layoutParams.getSpanIndex();

            if(mFirstStaggeredPosition % 2 == 0) {//第一个staggered下标position是偶数

                // 中间间隔
                if (spanIndex == 0) {
                    outRect.left = mSpace;
                    outRect.right = mSpace / 2;
                } else {
                    // item为奇数位，设置间隔
                    outRect.left = mSpace / 2;
                    outRect.right = mSpace;
                }
            } else {
                // 中间间隔
                if (spanIndex == 1) {
                    outRect.left = mSpace / 2;
                    outRect.right = mSpace;
                } else {
                    // item为奇数位，设置间隔
                    outRect.left = mSpace;
                    outRect.right = mSpace / 2;
                }
            }

            // 下方间隔
            outRect.bottom = mSpace;
        } else {
            outRect.left = 0;
            outRect.right = 0;

            outRect.bottom = 0;
        }
    }
}
